/*
 * comlan
 */

package com.promfy.util;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

public class NetUtil {

	public static class UDPMulticastServer {

		final static int RECEIVE_LENGTH = 1024;

		static final String multicastHost = "239.255.255.255";// 224.0.0.0到239.255.255.255

		static final int localPort = 1900;

		public static void receive() throws Exception {
			InetAddress receiveAddress = InetAddress.getByName(multicastHost);
			if (!receiveAddress.isMulticastAddress()) {// 测试是否为多播地址
				throw new Exception("请使用多播地址");
			}

			int port = localPort;
			MulticastSocket receiveMulticast = new MulticastSocket(port);
			receiveMulticast.joinGroup(receiveAddress);
			DatagramPacket dp = new DatagramPacket(new byte[RECEIVE_LENGTH], RECEIVE_LENGTH);
			receiveMulticast.receive(dp);
			System.out.println(new String(dp.getData()).trim());
			receiveMulticast.close();
		}
	}

	public static class UDPMulticastClient {
		static final String destAddressStr = "239.255.255.250";// 224.0.0.0到239.255.255.255
		static final int destPortInt = 1900;
		static final int TTLTime = 3;
		public static final String NEWLINE = "\n";

		public static void send() throws Exception {
			InetAddress destAddress = InetAddress.getByName(destAddressStr);
			if (!destAddress.isMulticastAddress()) {
				throw new Exception("地址不是多播地址");
			}
			int destPort = destPortInt;
			int TTL = TTLTime;
			MulticastSocket multiSocket = new MulticastSocket();
			multiSocket.setTimeToLive(TTL);

			//upnp sample
			StringBuilder content = new StringBuilder();
			content.append("M-SEARCH * HTTP/1.1").append(NEWLINE);
			content.append("Man: \"ssdp:discover\"").append(NEWLINE);
			content.append("Mx: 3").append(NEWLINE);
			content.append("Host: 239.255.255.250:1900").append(NEWLINE);
			content.append("St: ssdp:all").append(NEWLINE);
			content.append(NEWLINE);

			DatagramPacket dp = new DatagramPacket(content.toString().getBytes(), content.length(), destAddress, destPort);
			multiSocket.send(dp);
			multiSocket.close();
		}
	}
	
	

}
